package com.elight.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class MailUtils {
	private String smtpHost = ""; // smtp服务器
	private int port = 25;
	private String sendMailAddr = ""; // 发件人地址
	private String password = ""; // 密码
	private List<String> ccList = null; // 抄送地址
	private List<String> toList = null; // 收件人地址
	private List<String> attrList = null; // 附件地址
	private String subject = ""; // 邮件标题
	private String content = ""; // 正文内容
	private boolean isHtml = false; // 是否使用html;
	private boolean isAuth=true; // false
	private String sendUserNickName = ""; // 发件人昵称
	private boolean isSSL=false;

	public boolean isSSL() {
		return isSSL;
	}

	public void setSSL(boolean isSSL) {
		this.isSSL = isSSL;
	}

	public boolean sendMail() {
		//基础验证
		if (StringUtils.isEmpty(sendMailAddr)) {
			return false;
		}
		if (toList == null || toList.size() == 0) {
			return false;
		}
		if (StringUtils.isEmpty(smtpHost)) {
			return false;
		}
//		if (StringUtils.isEmpty(password)) {
//			return false;
//		}

		Properties props = new Properties();
		props.put("mail.smtp.host", smtpHost); // 指定主机
		props.put("mail.smtp.auth", isAuth?"true":"false"); // 是否需要验证
		if(!isSSL){
			props.put("mail.smtp.port", String.valueOf(port));
		}else{
			props.put("mail.smtp.socketFactory.port",  String.valueOf(port));      
        	props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");        
		} 
        Session session = Session.getDefaultInstance(props,new Authenticator()
        {             
        	protected PasswordAuthentication getPasswordAuthentication() 
        	{                   
        		return new PasswordAuthentication(sendMailAddr,password);               
        	}       
        });
		
	
		MimeMessage message = new MimeMessage(session);
		try {
			// 加载发件人地址
			InternetAddress from = null;
			if (!StringUtils.isEmpty(sendUserNickName)) {
				from = new InternetAddress(MimeUtility.encodeWord(sendUserNickName) + " <" + sendMailAddr + ">");
			} else {
				from = new InternetAddress(sendMailAddr);
			}
			message.setFrom(from);

			// 加载收件人地址
			List<InternetAddress> toMailInternetAddress = new ArrayList<InternetAddress>();
			for (String toMailAddr : toList) {
				if (Validation.isEmail(toMailAddr))//验证通过才放入集合中
					toMailInternetAddress.add(new InternetAddress(toMailAddr));
			}
			//判断验证后的集合是否为空
			if (toMailInternetAddress.size() == 0)
				return false;
			else {
				for(InternetAddress toMailAddress : toMailInternetAddress)
					message.addRecipient(Message.RecipientType.TO, toMailAddress);
				//message.setRecipients(Message.RecipientType.TO, (InternetAddress[]) toMailInternetAddress.toArray());
			}

			// 加载标题
			message.setSubject(subject);
			// 设置发送时间
			message.setSentDate(new Date());

			// 设置抄送
			if (ccList != null && ccList.size()>0) {
				for (String ccMailAddr : ccList) {
					if (Validation.isEmail(ccMailAddr))
						message.addRecipient(Message.RecipientType.CC, new InternetAddress(ccMailAddr));
				}
			}

			// 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
			Multipart multipart = new MimeMultipart();
			// 设置邮件的文本内容
			BodyPart contentPart = new MimeBodyPart();
			//添加正文内容，判断是否为html格式
			if(isHtml)
			{
				contentPart.setContent(content, "text/html;charset=utf-8");
				
			}else{
				contentPart.setText(content);
			}
			multipart.addBodyPart(contentPart);
			message.setContent(multipart);
			
			// 添加附件
			if(attrList!=null && attrList.size()>0){
				for(String filePath : attrList){
					BodyPart messageBodyPart = new MimeBodyPart();
					//获得附件
					File file =new File(filePath);
					if(!file.exists()){
						continue;
					}
					DataSource source = new FileDataSource(filePath);
					//设置附件的数据处理器
					messageBodyPart.setDataHandler(new DataHandler(source));
					//设置附件文件名
					// 这里很重要，通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
					//messageBodyPart.setFileName();
					messageBodyPart.setFileName("=?GBK?B?"+ Base64Utils.encode(file.getName().getBytes()) + "?=");
					multipart.addBodyPart(messageBodyPart);
				}
			}
			// 保存邮件
			message.saveChanges();
			
			//定义发送协议
			Transport transport = session.getTransport("smtp");
			// 连接服务器的邮箱
			transport.connect(smtpHost,sendMailAddr,password);
			//transport.connect();
			// 把邮件发送出去
			transport.send(message,message.getAllRecipients());
			transport.close();
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		}
	}

	public String getSmtpHost() {
		return smtpHost;
	}

	public void setSmtpHost(String smtpHost) {
		this.smtpHost = smtpHost;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getSendMailAddr() {
		return sendMailAddr;
	}

	public void setSendMailAddr(String sendMailAddr) {
		this.sendMailAddr = sendMailAddr;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public List<String> getCcList() {
		return ccList;
	}

	public void setCcList(List<String> ccList) {
		this.ccList = ccList;
	}

	public List<String> getToList() {
		return toList;
	}

	public void setToList(List<String> toList) {
		this.toList = toList;
	}

	public List<String> getAttrList() {
		return attrList;
	}
	public Boolean isAuth() {
		return isAuth;
	}

	public void setAuth(Boolean isAuth) {
		this.isAuth = isAuth;
	}

	

	public void setAttrList(List<String> attrList) {
		this.attrList = attrList;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public boolean isHtml() {
		return isHtml;
	}

	public void setHtml(boolean isHtml) {
		this.isHtml = isHtml;
	}

	public String getSendUserNickName() {
		return sendUserNickName;
	}

	public void setSendUserNickName(String sendUserNickName) {
		this.sendUserNickName = sendUserNickName;
	}
	
	public static void main(String[] args) {
		MailUtils m=new MailUtils();
		m.setSmtpHost("smtp.trans-cosmos.com.cn");
		m.setPort(25);//默认25
		m.setSSL(true);
		m.setAuth(true);
		m.setSendMailAddr("18862253202@qq.com");
		//m.setPassword("hohpzctzppxzbegh");//秘密
		m.setPassword(null);
		//m.setSendUserNickName("admin@trans-cosmos.com.cn");
		m.setSubject("做个测试");
		//设置收件人
		List<String> toList=new ArrayList<String>();
		toList.add("zhou.junwen@trans-cosmos.com.cn");
		m.setToList(toList);
		//设置抄送
//		List<String> ccList=new ArrayList<String>();
//		ccList.add("656098987@qq.com");
//		ccList.add("2427746718@qq.com");
//		m.setCcList(ccList);
		//设置附件
//		List<String> attrList=new ArrayList<String>();
//		attrList.add("d:/stc-isp-15xx-v6.85.rar");
//		attrList.add("d:/stc-isp-15xx-v6.85.exe");
//		m.setAttrList(attrList);
		//是否使用Html
		m.setHtml(true);
		m.setContent("<html><body><p style='color:red'>做个测试</p></body></html>");
		
		//m.setHtml(false);
		//m.setContent("做个测试");
		
		System.out.println(m.sendMail());
	}
}
